<?php
declare (strict_types=1);

namespace app\adminapi\validate\passport;

use kitego\extend\login\admin\enum\AdminLoginEnum;
use think\Validate;

class PassportValidate extends Validate
{
    private const PASSWORD_LOGIN = AdminLoginEnum::PASSWORD;
    private const GITEE_LOGIN = AdminLoginEnum::GITEE;

    /**
     * 定义验证规则
     * 格式：'字段名' =>  ['规则1','规则2'...]
     *
     * @var array
     */
    protected $rule = [
        'account|登录账号' => 'requireIf:loginWay,' . self::PASSWORD_LOGIN . '|max:55',
        'password|密码' => 'requireIf:loginWay,' . self::PASSWORD_LOGIN .'|max:32',
        'code|gitee授权码' => 'requireIf:loginWay,' . self::GITEE_LOGIN,
        'captchaType|验证码方式' => ['in' => [1, 2], 'checkCaptchaType'],
        'loginWay|登录方式' => ['require', 'in' => [AdminLoginEnum::PASSWORD, AdminLoginEnum::GITEE]],
        'refreshToken|刷新token' => 'require',
    ];

    /**
     * 定义错误信息
     * 格式：'字段名.规则名' =>  '错误信息'
     *
     * @var array
     */
    protected $message = [];

    /**
     * 验证场景定义
     * @var array
     */
    protected $scene = [
        'getToken' => ['account', 'password', 'captchaType', 'loginWay', 'code'],
        'refreshToken' => ['refreshToken'],
    ];

    /**
     * 校验不同验证方式所需参数
     * @param $value
     * @param $rule
     * @param array $data
     * @return string|true
     */
    protected function checkCaptchaType($value, $rule, array $data = []): bool|string
    {
        if ($value == 1) {
            // 验证码方式
            if (!isset($data['captcha'])) {
                return '验证码必填';
            }
        } elseif ($value == 2) {
            // 点选验证码方式
            if (!isset($data['captcha']) || !isset($data['captchaId']) || !is_numeric($data['captchaId'])) {
                return '点选验证码必填';
            }
        }

        return true;
    }
}
